package com.abdosoft.core;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.StringUtils;

/**
 * 日期工具类。
 * 
 * @author  覃寿仙
 */
public class DateUtil {

	public static String formatDate(Date date, String pattern) {
		if (date == null)
			return "";
		if (pattern == null)
			pattern = "yyyy-MM-dd";
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		return (sdf.format(date));
	}

	public static String getDatePath(Date d) {
		Calendar c = Calendar.getInstance();
		c.setTime(d);
		StringBuffer path = new StringBuffer();
		path.append("/");
		path.append(c.get(Calendar.YEAR));
		path.append("/");
		path.append(c.get(Calendar.MONTH) + 1);
		path.append("/");
		path.append(c.get(Calendar.DATE));
		return path.toString();
	}

	public static String formatDateTime(Date date) {
		return (formatDate(date, "yyyy-MM-dd HH:mm:ss"));
	}

	public static String formatDateTime() {
		return (formatDate(now(), "yyyy-MM-dd HH:mm:ss"));
	}

	public static String formatDate(Date date) {
		return (formatDate(date, "yyyy-MM-dd"));
	}

	/**
	 * 上月末日期
	 * 
	 * @param date
	 * @return String  
	 */
	public static Date getLastMonthDay() {
		String dates = formatDate(new Date());
		String datess[] = dates.split("-");
		dates = datess[0] + "-" + datess[1] + "-" + "01";
		Date lastMonthDay = new Date(parseDate(dates).getTime() - 1000 * 3600 * 24);
		return lastMonthDay;
	}

	/**
	 * 新增一个日期转化为数字格式的方法
	 * 
	 * @param date
	 * @return String  
	 */
	public static String formatDate2(Date date) {
		return (formatDate(date, "yyyyMMdd"));
	}
	public static String formatDate2() {
		return (formatDate(now(), "yyyyMMdd"));
	}
	
	public static String formatHour() {
		return (formatDate(now(), "HH"));
	}

	public static String formatDate() {
		return (formatDate(now(), "yyyy-MM-dd"));
	}
	public static String formatDateTimeNow2() {
		return (formatDate(now(), "yyyyMMddHHmmss"));
	}
	
	public static String formatDateTimeNow() {
		return (formatDate(now(), "yyyy-MM-dd HH:mm:ss"));
	}
	public static String formatDateTimeNow(Date date) {
		return (formatDate( date, "yyyy-MM-dd HH:mm:ss"));
	}

	public static String formatTime(Date date) {
		return (formatDate(date, "HH:mm:ss"));
	}

	public static String formatTime() {
		return (formatDate(now(), "HH:mm:ss"));
	}

	public static String formatTime2() {
		return (formatDate(now(), "HHmmss"));
	}
	public static String formatTime3() {
		return (formatDate(now(), "HHmmssSSS"));
	}
	

	public static Date now() {
		return (new Date());
	}

	public static Date parseDateTime(String datetime) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		if ((datetime == null) || (datetime.equals(""))) {
			return null;
		} else {
			try {
				return formatter.parse(datetime);
			} catch (ParseException e) {
				return parseDate(datetime);
			}
		}
	}

	public static Date parseDate(String date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		if ((date == null) || (date.equals(""))) {
			return null;
		} else {
			try {
				return formatter.parse(date);
			} catch (ParseException e) {
				return null;
			}
		}
	}

	public static Date parseDate2(String date) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");

		if ((date == null) || (date.equals(""))) {
			return null;
		} else {
			String tdate=date;
			try { 
				return formatter.parse(date.replaceAll("-", "").replaceAll("/", ""));
			} catch (ParseException e) {
				try {
					formatter = new SimpleDateFormat("MM/dd/yy");
					return formatter.parse(tdate);
				} catch (ParseException ee) {
					try {
						formatter = new SimpleDateFormat("MM/dd/yyyy");
						return formatter.parse(tdate);
					} catch (ParseException eee) {
						eee.printStackTrace(); 
						return null;
					}
				}
				
			}
		}
	}

	public static Date parseDate(Date datetime) {
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

		if (datetime == null) {
			return null;
		} else {
			try {
				return formatter.parse(formatter.format(datetime));
			} catch (ParseException e) {
				return null;
			}
		}
	}

	public static String formatDate(Object o) {
		if (o == null)
			return "";
		if (o.getClass() == String.class)
			return formatDate(o);
		else if (o.getClass() == Date.class)
			return formatDate((Date) o);
		else if (o.getClass() == Timestamp.class) {
			return formatDate(new Date(((Timestamp) o).getTime()));
		} else
			return o.toString();
	}

	public static String formatDateTime(Object o) {
		if (o.getClass() == String.class)
			return formatDateTime(o);
		else if (o.getClass() == Date.class)
			return formatDateTime((Date) o);
		else if (o.getClass() == Timestamp.class) {
			return formatDateTime(new Date(((Timestamp) o).getTime()));
		} else
			return o.toString();
	}

	/**
	 * 给时间加上或减去指定毫秒，秒，分，时，天、月或年等，返回变动后的时间
	 * 
	 * @param date
	 *            要加减前的时间，如果不传，则为当前日期
	 * @param field
	 *            时间域，有Calendar.MILLISECOND,Calendar.SECOND,Calendar.MINUTE,<br>
	 *            Calendar.HOUR,Calendar.DATE, Calendar.MONTH,Calendar.YEAR
	 * @param amount
	 *            按指定时间域加减的时间数量，正数为加，负数为减。
	 * @return 变动后的时间
	 */
	public static Date add(Date date, int field, int amount) {
		if (date == null) {
			date = new Date();
		}
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.add(field, amount);

		return cal.getTime();
	}

	public static Date addMilliSecond(Date date, int amount) {
		return add(date, Calendar.MILLISECOND, amount);
	}

	public static Date addSecond(Date date, int amount) {
		return add(date, Calendar.SECOND, amount);
	}

	public static Date addMiunte(Date date, int amount) {
		return add(date, Calendar.MINUTE, amount);
	}

	public static Date addHour(Date date, int amount) {
		return add(date, Calendar.HOUR, amount);
	}

	public static Date addDay(Date date, int amount) {
		return add(date, Calendar.DATE, amount);
	}

	public static Date addMonth(Date date, int amount) {
		return add(date, Calendar.MONTH, amount);
	}

	public static Date addYear(Date date, int amount) {
		return add(date, Calendar.YEAR, amount);
	}

	public static Date getDate() {
		return parseDate(formatDate());
	}

	public static Date getDateTime() {
		return parseDateTime(formatDateTime());
	}

	public static String getDateStrByTime(long time) {
		Date date = new Date(time);
		return date.toLocaleString().substring(0, date.toLocaleString().indexOf(" "));
	}

	public static String getDateStrByAnyDate(String str) {
		System.out.println(str);
		if (str.length() == 8 && str.indexOf("-") < 0 && str.indexOf("/") < 0) {
			return DateUtil.formatDate(DateUtil.parseDate2(str));
		}

		// str= 2011-01-01； 2011-1-1； 2011/1/1; 2011/01/01； 2011\1\1; 2011\01\01
		String[] tmp = null;
		if (str.indexOf("-") > 0)
			tmp = str.split("-");

		if (str.indexOf("/") > 0)
			tmp = str.split("/");

		// if(str.indexOf("\\") > 0)
		// tmp = str.split("\\");

		String year = StringUtils.trim(tmp[0]);
		String month = StringUtils.trim(tmp[1]);
		String day = StringUtils.trim(tmp[2]);

		if (month.length() == 1)
			month = "0" + month;

		if (day.length() == 1)
			day = "0" + day;

		return year + "-" + month + "-" + day;
	}
	
	static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
	/**
	* 获取日期年份
	* @param date
	* @return
	* @throws ParseException
	*/
	public static int getYear(String date)  {
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(dateFormat.parse(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return calendar.get(Calendar.YEAR);
	}
	
	/**
	* 获取日期月份
	* @param date
	* @return
	* @throws ParseException
	*/
	public static int getMonth(String date) {
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(dateFormat.parse(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return (calendar.get(Calendar.MONTH) + 1);
	}
	
	/**
	* 获取日期号
	* @param date
	* @return
	* @throws ParseException
	*/
	public static int getDay(String date) {
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(dateFormat.parse(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return calendar.get(Calendar.DAY_OF_MONTH);
	}
	/**
	* 获取月份起始日期
	* @param date
	* @return
	* @throws ParseException
	*/
	public static String getMinMonthDate(String date)  {
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(dateFormat.parse(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
		return dateFormat.format(calendar.getTime());
	}
	
	/**
	* 获取月份最后日期
	* @param date
	* @return
	* @throws ParseException
	*/
	public static String getMaxMonthDate(String date)  {
		Calendar calendar = Calendar.getInstance();
		try {
			calendar.setTime(dateFormat.parse(date));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
		return dateFormat.format(calendar.getTime());
	}
 
	//返回秒
	public static   long  getSecond(){
		return new Date().getTime()/1000;
	}
	
	public static long  getSecondFromDate(String strDate ){ 
		//String strDate = "2001-03-15 15-37-05";  
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//24小时制  
//      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制  
        long time2=0; 
			try {
				time2 = simpleDateFormat.parse(strDate).getTime();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
        //System.out.println(time2);  
		return time2/1000; 
	}
	
	//秒转日期
	public static String  getDateFromSecond(long second ){
		//Date date2 = new Date();
        //date2.setTime(second * 1000);
        //return formatDateTime(date2);
		if(second==0){
			return  formatDateTime(new Date() );
		}
       
       return  formatDateTime(new Date( second * 1000 ) );
	} 

	public static void main(String[] args) {
		// System.out.println(DateUtil.getDateStrByAnyDate("2011-01-01"));
		// System.out.println(DateUtil.getDateStrByAnyDate("2011-1-1"));
		// System.out.println(DateUtil.getDateStrByAnyDate("2011/1/1"));
		// System.out.println(DateUtil.getDateStrByAnyDate("2011/01/01"));
		// System.out.println(DateUtil.getDateStrByAnyDate("20110101"));
		System.out.println(DateUtil.getLastMonthDay());

		// System.out.println(DateUtil.getDateStrByAnyDate("2011\1\1"));
		// System.out.println(DateUtil.getDateStrByAnyDate("2011\01\01 "));
		
		
		String date = "2011-04-25 22:28:30";
		System.out.println(date);
		System.out.println("年份：" + getYear(date));
		System.out.println("月份：" + getMonth(date));
		System.out.println("日期：" + getDay(date));
		System.out.println("月初日期是: " + getMinMonthDate(date));
		System.out.println("月末日期是: " + getMaxMonthDate(date));
		
		try {
		//输入日期转化为毫秒数 ---用calendar方法（calendar.getTime）  
        Calendar calendar = Calendar.getInstance();  
        calendar.set(2018, 2, 15, 8, 31, 5);  
        System.out.println(calendar.getTimeInMillis());  
        
		//输入日期，转化为毫秒数，用DATE方法()  
        /**  
         * 先用SimpleDateFormat.parse() 方法将日期字符串转化为Date格式  
         * 通过Date.getTime()方法，将其转化为毫秒数  
         */  
        String datex = "2001-03-15 15-37-05";  
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");//24小时制  
//      SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");//12小时制  
        long time2; 
			time2 = simpleDateFormat.parse(datex).getTime();

        System.out.println(time2);  
		
		//输入毫秒数，转化为日期，用simpleDateFormat  +  Date 方法；  
        /**  
         * 直接用SimpleDateFormat格式化 Date对象，即可得到相应格式的日期 字符串。  
         */  
        long time3 = System.currentTimeMillis() + 5000 *1000;  
          
        Date date2 = new Date();  
        date2.setTime(time3);  
        System.out.println(simpleDateFormat.format(date2));  
		
		//输入毫秒数，转化为日期，用calendar方法；  
        Calendar calendar2 = Calendar.getInstance();  
        calendar2.setTimeInMillis(time3);  
        int year = calendar2.get(Calendar.YEAR);  
        int month = calendar2.get(Calendar.MONTH);  
        int day = calendar2.get(Calendar.DAY_OF_MONTH);  
        int hour = calendar2.get(Calendar.HOUR_OF_DAY);//24小时制  
//      int hour = calendar2.get(Calendar.HOUR);//12小时制  
        int minute = calendar2.get(Calendar.MINUTE);  
        int second = calendar2.get(Calendar.SECOND);  
          
        System.out.println(year + "年" + (month + 1) + "月" + day + "日"  
                + hour + "时" + minute + "分" + second + "秒");  
		
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
	}
}
